#!/bin/bash
# 在本目录执行脚本
shDir=$(cd `dirname $0`; pwd)
cd ${shDir}

# 变量声明
. ../func/const.sh
. ../func/pm.sh

echo -e '\e[36m基础包安装\e[0m'

# 包管理器检测
PM=$(pmDetect)

if [[ "${PM}" == "unknown" ]]; then
    echo "❌ 无法识别系统类型或不支持的发行版"
    exit 1
fi

echo "✅ 检测到包管理器：\e[36m${PM}\e[0m"

# 定义对应包列表文件路径
PKG_FILE="./${PM}"

# 检查包列表文件是否存在
if [[ ! -f "${PKG_FILE}" ]]; then
    echo "⚠️  包列表文件不存在: ${PKG_FILE}"
    echo "💡 请创建该文件并添加要安装的软件包（每行一个）"
    exit 1
fi

echo "📁 读取包列表: ${PKG_FILE}"

# 读取包列表
PACKAGES=$(readPackagesFromFile "${PKG_FILE}")
if [[ $? -ne 0 ]]; then
    echo "❌ 读取包列表失败"
    exit 1
fi

if [[ -z "${PACKAGES}" ]]; then
    echo "📦 包列表为空，无需安装"
    exit 0
fi

echo "📥 即将安装的软件包: ${PACKAGES}"

# 确认安装（可选，生产环境可注释）
read -p "🚀 确认安装？[Y/n]: " -n 1 -r
echo
if [[ ! "${REPLY}" =~ ^[Yy]$|^$ ]]; then
    echo "❌ 安装已取消"
    exit 1
fi

# 执行安装
echo "🔧 正在安装软件包..."

case "${PM}" in
    "apt")
        apt update || { echo "❌ apt update 失败"; exit 1; }
        apt install -y "${PACKAGES}" || { echo "❌ apt 安装失败"; exit 1; }
        ;; 

    "dnf")
        dnf -y install "${PACKAGES}" || { echo "❌ dnf 安装失败"; exit 1; }
        ;;

    "yum")
        yum -y install "${PACKAGES}" || { echo "❌ yum 安装失败"; exit 1; }
        ;;

    "pacman")
        pacman -Sy --noconfirm "${PACKAGES}" || { echo "❌ pacman 安装失败"; exit 1; }
        ;;

    "zypper")
        zypper install -y "${PACKAGES}" || { echo "❌ zypper 安装失败"; exit 1; }
        ;;

    "apk")
        apk add "${PACKAGES}" || { echo "❌ apk 安装失败"; exit 1; }
        ;;

    "emerge")
        emerge --ask=n "${PACKAGES}" || { echo "❌ emerge 安装失败"; exit 1; }
        ;;

    *)
        echo "❌ 不支持的包管理器: ${PM}"
        exit 1
        ;;
esac

echo "🎉 所有软件包安装完成！"